package cn.iocoder.ny.module.mall.utils;

import org.springframework.mock.web.MockMultipartFile;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.geom.Ellipse2D;
import java.awt.geom.RoundRectangle2D;
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.URL;

public class PosterUtils {

    public static BufferedImage createImage() throws Exception {
        Font regularFont = new Font("PingFang SC Regular", Font.BOLD, 12 * 3);
        Font mediumFont = new Font("PingFang SC Medium", Font.BOLD, 15 * 3);

        // 读取主图
        BufferedImage posterBufImage = ImageIO.read(new URL("https://www.51poster.com/app/design/template/2bca581b-c87a-4c68-bfae-c9845336b31f/66deac893190.png"));
        int posterWidth = posterBufImage.getWidth();
        int posterHeight = posterBufImage.getHeight();

        // 画布的宽度固定为主图的宽度，高度为主图高度加上一些额外的空间
        int width = posterWidth;
        int height = posterHeight + 300;

        // 创建画布
        BufferedImage bgBufImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
        Graphics2D graphics = bgBufImage.createGraphics();
        graphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

        // 设置背景颜色
        graphics.setBackground(Color.WHITE);
        graphics.clearRect(0, 0, width, height);
        graphics.setBackground(new Color(255, 255, 255));

        // 读取头像图像
        BufferedImage headImage = ImageIO.read(new URL("" +
                "/it/u=4113075832,3609938507&fm=253&app=120&size=w931&n=0&f=JPEG&fmt=auto?sec=1731344400&t=81e4e4b5572342088a6b444e89f2e521"));

        // 创建圆形头像
        BufferedImage roundHeadImg = new BufferedImage(headImage.getWidth(), headImage.getHeight(), BufferedImage.TYPE_INT_ARGB);
        Graphics2D roundHeadGraphics = roundHeadImg.createGraphics();
        Ellipse2D.Double shape = new Ellipse2D.Double(0, 0, roundHeadImg.getWidth(), roundHeadImg.getHeight());
        roundHeadGraphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        roundHeadGraphics.setClip(shape);
        roundHeadGraphics.drawImage(headImage, 0, 0, null);
        roundHeadGraphics.dispose();

        // 绘制主图
        graphics.drawImage(posterBufImage, 0, 0, posterWidth, posterHeight, null);
        // 绘制圆形头像
        graphics.drawImage(roundHeadImg, 10, posterHeight + 20, 150, 150, null);

        // 设置字体和绘制文本
        graphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        regularFont = regularFont.deriveFont(Font.BOLD, 12 * 3);
        graphics.setFont(regularFont);
        mediumFont = mediumFont.deriveFont(Font.BOLD, 15 * 3);
        graphics.setPaint(new Color(51, 51, 51));
        graphics.setFont(mediumFont);
        graphics.drawString("昵称", 170, posterHeight + 80);

        regularFont = regularFont.deriveFont(Font.BOLD, 11 * 3);
        graphics.setPaint(new Color(102, 102, 102));
        graphics.setFont(regularFont);
        drawStringWithFontStyleLineFeed(graphics, "邀请你来参加活动", width - 100, 20, posterHeight + 120, regularFont);

        // 绘制二维码
        BufferedImage qrCodeImage = QRCodeUtils.encode("www.baidu.com", false);
        graphics.drawImage(qrCodeImage, width - 220, posterHeight + 150, 150, 150, null);

        // 绘制底部logo
        InputStream logoFontInputStream = new FileInputStream("C:\\Users\\Windows\\Pictures\\微信图片_20240914140137.png");
        BufferedImage logFontImage = ImageIO.read(logoFontInputStream);
        graphics.drawImage(logFontImage, 10, height - 80, 300, 60, null);

        // 释放资源
        graphics.dispose();

        return bgBufImage;
    }

    private static void drawStringWithFontStyleLineFeed(Graphics2D g, String strContent, int maxWidth, int loc_X, int loc_Y, Font font) {
        g.setFont(font);
        int strWidth = getStringLength(g, strContent);
        int strHeight = getStringHeight(g);
        if (strWidth > maxWidth) {
            int rowStrNum = getRowStrNum(strContent.length(), maxWidth, strWidth);
            int rows = getRows(strWidth, maxWidth);
            for (int i = 0; i < 2; i++) {
                String temp = "";
                if (i == 1) {
                    if (rows == 2) {
                        temp = strContent.substring(i * rowStrNum);
                    } else {
                        temp = strContent.substring(i * rowStrNum, (i + 1) * rowStrNum - 1);
                        temp = "\n" + temp + "...";
                    }
                    loc_Y = loc_Y + strHeight;
                }
                if (i == 0) {
                    temp = strContent.substring(0, rowStrNum);
                }
                g.drawString(temp, loc_X, loc_Y);
            }
        } else {
            g.drawString(strContent, loc_X, loc_Y);
        }
    }

    private static int getStringLength(Graphics g, String str) {
        char[] strcha = str.toCharArray();
        return g.getFontMetrics().charsWidth(strcha, 0, str.length());
    }

    private static int getStringHeight(Graphics g) {
        return g.getFontMetrics().getHeight();
    }

    private static int getRowStrNum(int strnum, int rowWidth, int strWidth) {
        return (rowWidth * strnum) / strWidth;
    }

    private static int getRows(int strWidth, int rowWidth) {
        return (strWidth % rowWidth > 0) ? strWidth / rowWidth + 1 : strWidth / rowWidth;
    }

    public InputStream getResourceStream(String filePath) {
        return this.getClass().getResourceAsStream(filePath);
    }

    public MultipartFile getFile(BufferedImage bufferedImage) throws Exception {
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        ImageIO.write(bufferedImage, "png", os);
        InputStream input = new ByteArrayInputStream(os.toByteArray());
        return new MockMultipartFile("file", "file.png", "text/plain", input);
    }

    public MultipartFile createQrCode(String qrCodeContent) {
        MultipartFile multipartFile = null;
        try {
            BufferedImage bufferedImage = QRCodeUtils.encode(qrCodeContent, false);
            ByteArrayOutputStream os = new ByteArrayOutputStream();
            ImageIO.write(bufferedImage, "jpg", os);
            InputStream input = new ByteArrayInputStream(os.toByteArray());
            multipartFile = new MockMultipartFile("file", "file.jpg", "text/plain", input);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return multipartFile;
    }

    public static void main(String[] args) {
        try {
            BufferedImage image = PosterUtils.createImage();
            ImageIO.write(image, "png", new File("C:\\Users\\Windows\\Pictures\\渲染效果二.jpg"));
            System.out.println("***********图片合成了********");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
